package com.sendpo.zjx.sendpo.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableRecyclerView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.LoginActivity;
import com.sendpo.zjx.sendpo.activity.UserPersonCenterGuestActivity;
import com.sendpo.zjx.sendpo.domain.UserPersonCenterDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by zjx on 2018
 */

public class MyQuanziFragment extends BaseMainFragment {

    private RecylcerAdaper adpter;
    public int currentlastitem = 0;
    public boolean lastloading = false;
    public LinearLayoutManager lm;
    private int pagenow = 1;
    @BindView(R.id.recyclerview)
    PullableRecyclerView recyclerview;
    View rootView = null;
    @BindView(value = R.id.pulltofresh)
    PullToRefreshLayout pulltofresh;


    public View initView()
    {
        View localView = View.inflate(this.mActivity, R.layout.fragment_yanchusaishi_layout, null);
        ButterKnife.bind(localView, this.mActivity);
        return localView;
    }

    public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
    {
        if (this.rootView == null)
        {
            this.rootView = super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
            ButterKnife.bind(this, this.rootView);
            initData();
        }
        return this.rootView;
    }

    private void initData() {
        this.lm = new LinearLayoutManager(this.mActivity, 1, false);
        this.recyclerview.setLayoutManager(this.lm);
        List<UserPersonCenterDomain.DataBean> dataBeans=new ArrayList<>();
        recyclerview.setAdapter(adpter=new RecylcerAdaper(dataBeans,mActivity));
        pulltofresh.setPullUpEnable(false);
        pulltofresh.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                List<User> userList=Xutils.queryAll(getActivity().getApplication(),User.class);
                if(userList!=null&&userList.size()!=0){
                    pagenow=1;
                    query(pagenow,userList.get(0).getUserId());
                }else{
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                        }
                    });
                }
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
            }
        });

        pulltofresh.autoRefresh();


    }

    @Override
    public void onStart() {
        super.onStart();


    }

    public  void query(final int pagenow , final int userId){
        Map<String,String>  map= new HashMap();
        map.put("pagenow", pagenow + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.dynamicById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                pulltofresh.refreshFinish(PullToRefreshLayout.SUCCEED);
                Gson gson=new Gson();
                UserPersonCenterDomain domain=gson.fromJson(result,UserPersonCenterDomain.class);
                switch (domain.getState()){
                    case HttpCode.SUCCESS:
                        if(adpter==null){
                            recyclerview.setAdapter(adpter=new RecylcerAdaper(domain.getData(),mActivity));
                            recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                @Override
                                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                    super.onScrollStateChanged(recyclerView, newState);
                                    if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                        if (MyQuanziFragment.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                            MyQuanziFragment.this.pagenow++;
                                            append(MyQuanziFragment.this.pagenow, userId);
                                        }
                                    }
                                }

                                @Override
                                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                    super.onScrolled(recyclerView, dx, dy);
                                    currentlastitem = lm.findLastVisibleItemPosition();
                                }
                            });
                        }else{
                            adpter.initRefresh(domain.getData());
                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pulltofresh.refreshFinish(PullToRefreshLayout.FAIL);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public  void append(final int pagenow , final int userId){
        lastloading=true;
        Map<String,String>  map= new HashMap();
        map.put("pagenow", pagenow + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.dynamicById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading=false;
                Gson gson=new Gson();
                UserPersonCenterDomain domain=gson.fromJson(result,UserPersonCenterDomain.class);
                switch (domain.getState()){
                    case HttpCode.SUCCESS:
                        if(adpter==null){
                            recyclerview.setAdapter(adpter=new RecylcerAdaper(domain.getData(),mActivity));
                            recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                @Override
                                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                    super.onScrollStateChanged(recyclerView, newState);
                                    if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                        if (MyQuanziFragment.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                            MyQuanziFragment.this.pagenow++;
                                            append(MyQuanziFragment.this.pagenow, userId);
                                        }
                                    }
                                }

                                @Override
                                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                    super.onScrolled(recyclerView, dx, dy);
                                    currentlastitem = lm.findLastVisibleItemPosition();
                                }
                            });
                        }else{
                            adpter.initAppend(domain.getData());
                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading=false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<UserPersonCenterDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<UserPersonCenterDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_genericuserguest_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final UserPersonCenterDomain.DataBean dataBean=dataBeen.get(position);
            ih.civ.setImageResource(R.drawable.nim_avatar_default);
            Glide.with(mActivity)
                    .load(""+dataBean.getUseravatar())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .override(300, 300)
                    .centerCrop()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.civ.setImageBitmap(resource);
                        }
                    });
            ih.uname.setText(""+dataBean.getUsername());
            ih.watchnum.setText(""+dataBean.getDynamicLooknumber());
            ih.datetime.setText(""+new SimpleDateFormat("yyyy年MM月dd日").format(Tools.getStringtoDate(dataBean.getDynamicCreatetime(),"yyyy-MM-dd HH:mm:ss")));
            ih.content.setText(""+dataBean.getDynamicComment());
            ih.all_ll.removeAllViews();
            List<String> imgs = dataBean.getImgs();
            if (imgs != null && imgs.size() != 0) {
                final List<String> ivs_s = new ArrayList<>();
                final List<ImageView> ivs = new ArrayList<>();
                for (String img : imgs) {
                    final ImageView iv = new ImageView(mActivity);
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(158), DensityUtil.dip2px(158));
                    lp.setMargins(DensityUtil.dip2px(10), 0, DensityUtil.dip2px(10), 0);
                    iv.setLayoutParams(lp);
                    iv.setBackgroundColor(getResources().getColor(R.color.default_lightgray));
                    Glide.with(mActivity)
                            .load(img)
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .override(500, 500)
                            .into(iv);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mActivity.vImageWatcher.show(iv, ivs, ivs_s);
                        }
                    });
                    ivs.add(iv);
                    ivs_s.add(img);
                    ih.all_ll.addView(iv);
                }
            }
            if(dataBean.isDynamicpraiseState()){
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
            }else{
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);

            }
            ih.goods_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    List<User> userList= Xutils.queryAll(mActivity.getApplication(),User.class);
                    if(userList==null||userList.size()==0){
                        Tools.redirectActivity(mActivity,LoginActivity.class);
                        return;
                    }
                    if(dataBean.isDynamicpraiseState()){
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);
                        dataBean.setDynamicpraiseState(false);
                        int count=Integer.parseInt(ih.goood_tv.getText().toString().trim()+"");
                        count--;
                        ih.goood_tv.setText(count+"");
                        nofocus(userList.get(0).getUserId()+"",dataBean.getDynamicId()+"");
                    }else{
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
                        dataBean.setDynamicpraiseState(true);
                        int count=Integer.parseInt(ih.goood_tv.getText().toString().trim()+"");
                        count++;
                        ih.goood_tv.setText(count+"");
                        focus(userList.get(0).getUserId()+"",dataBean.getDynamicId()+"");
                    }
                }
            });
            ih.goood_tv.setText(""+dataBean.getDynamicPraiseCount());
            ih.guest_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("data",dataBean);
                    Tools.redirectActivity(mActivity,UserPersonCenterGuestActivity.class,map);
                }
            });
            ih.watch_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("data",dataBean);
                    Tools.redirectActivity(mActivity,UserPersonCenterGuestActivity.class,map);
                }
            });
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("data",dataBean);
                    Tools.redirectActivity(mActivity,UserPersonCenterGuestActivity.class,map);
                }
            });
            ih.all_ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("data",dataBean);
                    Tools.redirectActivity(mActivity,UserPersonCenterGuestActivity.class,map);
                }
            });
            ih.guest_tv.setText(""+dataBean.getGuestcount());
            if(dataBean.getUsersex()==0){
                ih.sex_rl.setBackgroundColor(getResources().getColor(R.color.default_blue));
                ih.sex_iv.setImageResource(R.mipmap.sex_male_while);
            }else{
                ih.sex_rl.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                ih.sex_iv.setImageResource(R.mipmap.sex_female_while);
            }
            ih.sex_tv.setText(""+dataBean.getUserage());

        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public LinearLayout all_ll;
            public CircleImageView civ;
            public TextView uname;
            public TextView datetime;
            public TextView watchnum;
            public ImageView goods_iv;
            public TextView content;
            public RelativeLayout goods_bt;
            public TextView goood_tv;
            public RelativeLayout guest_bt;
            public RelativeLayout watch_bt;
            public TextView guest_tv;

            public RelativeLayout sex_rl;
            public ImageView sex_iv;
            public TextView sex_tv;
            public TextView location_tv;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                all_ll = itemView.findViewById(R.id.all_ll);
                civ = itemView.findViewById(R.id.cir_icon);
                uname=itemView.findViewById(R.id.uname);
                datetime=itemView.findViewById(R.id.datetime);
                watchnum=itemView.findViewById(R.id.watchnum);
                goods_iv= itemView.findViewById(R.id.goods_iv);
                content=itemView.findViewById(R.id.content);
                goods_bt=itemView.findViewById(R.id.goods_bt);
                goood_tv=itemView.findViewById(R.id.goood_tv);
                guest_bt=itemView.findViewById(R.id.guest_bt);
                watch_bt=itemView.findViewById(R.id.watch_bt);
                guest_tv=itemView.findViewById(R.id.guest_tv);
                sex_rl=itemView.findViewById(R.id.sex_rl);
                sex_iv=itemView.findViewById(R.id.sex_iv);
                sex_tv=itemView.findViewById(R.id.sex_tv);
                location_tv=itemView.findViewById(R.id.location_tv);
            }
        }

        public void initRefresh(List<UserPersonCenterDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<UserPersonCenterDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }

        public  void focus(String userId,String dynamicId){
            Map<String,String> map=new HashMap<>();
            map.put("userId",""+userId);
            map.put("dynamicId",dynamicId);
            Xutils.POST(HttpUrl.userdynamicpraiseAdd, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        public  void  nofocus(String userId,String dynamicId){
            Map<String,String> map=new HashMap<>();
            map.put("userId",""+userId);
            map.put("dynamicId",dynamicId);
            Xutils.POST(HttpUrl.userdynamicpraiseDelete, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
    }
}
